﻿#include "SizePolicyEditEntry.h"
#include "EnumEditEntry.h"
#include "IntegerEditEntry.h"

#include <QSizePolicy>
#include <QPointer>
#include <QMetaEnum>


struct SizePolicyEditEntry::SizePolicyEntryPrivate {
    QPointer<EnumEditEntry> entryHorizontalPolicy;
    QPointer<EnumEditEntry> entryVerticalPolicy;
    QPointer<IntegerEditEntry> entryHorizontalStretch;
    QPointer<IntegerEditEntry> entryVerticalStretch;
};

SizePolicyEditEntry::~SizePolicyEditEntry() {
}

SizePolicyEditEntry::SizePolicyEditEntry(QWidget *parent) : StringEditEntry{parent} {
    p.reset(new SizePolicyEntryPrivate);
    initUi();
    retranslateUi();
}

void SizePolicyEditEntry::setValue(const QSizePolicy &policy) {
    QMetaEnum metaEnum = QMetaEnum::fromType<QSizePolicy::Policy>();
    QString text = QString("[%1,%2,%3,%4]")
                       .arg(metaEnum.valueToKey(policy.horizontalPolicy()))
                       .arg(metaEnum.valueToKey(policy.verticalPolicy()))
                       .arg(policy.horizontalStretch())
                       .arg(policy.verticalStretch());
    StringEditEntry::setValue(text);
    p->entryHorizontalPolicy->setValue(policy.horizontalPolicy());
    p->entryVerticalPolicy->setValue(policy.verticalPolicy());
    p->entryHorizontalStretch->setValue(policy.horizontalStretch());
    p->entryVerticalStretch->setValue(policy.verticalStretch());
}

QSizePolicy SizePolicyEditEntry::value() const {
    QSizePolicy policy;
    policy.setHorizontalPolicy(QSizePolicy::Policy(p->entryHorizontalPolicy->value()));
    policy.setVerticalPolicy(QSizePolicy::Policy(p->entryVerticalPolicy->value()));
    policy.setHorizontalStretch(p->entryHorizontalStretch->value());
    policy.setVerticalStretch(p->entryVerticalStretch->value());
    return policy;
}

void SizePolicyEditEntry::onChildEntryValueChanged() {
    emit valueChanged(value());
}

void SizePolicyEditEntry::initUi() {
    p->entryHorizontalPolicy = new EnumEditEntry;
    p->entryHorizontalPolicy->setMetaEnum(QMetaEnum::fromType<QSizePolicy::Policy>());
    appendChildEntry(p->entryHorizontalPolicy);

    p->entryVerticalPolicy = new EnumEditEntry;
    p->entryVerticalPolicy->setMetaEnum(QMetaEnum::fromType<QSizePolicy::Policy>());
    appendChildEntry(p->entryVerticalPolicy);

    p->entryHorizontalStretch = new IntegerEditEntry;
    appendChildEntry(p->entryHorizontalStretch);

    p->entryVerticalStretch = new IntegerEditEntry;
    appendChildEntry(p->entryVerticalStretch);
}

void SizePolicyEditEntry::retranslateUi() {
    p->entryHorizontalPolicy->setTitle(tr("Horizontal policy"));
    p->entryVerticalPolicy->setTitle(tr("Vertical policy"));
    p->entryHorizontalStretch->setTitle(tr("Horizontal stretch"));
    p->entryVerticalStretch->setTitle(tr("Vertical stretch"));
}
